package sanrenxing.dayEnd.backRepertoryTotal.controller;

import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import sanrenxing.dayEnd.backRepertoryTotal.domain.MarketData;
import sanrenxing.dayEnd.backRepertoryTotal.domain.MarketDataT;
import sanrenxing.dayEnd.backRepertoryTotal.service.MarketDataService;
import sanrenxing.dayEnd.backRepertoryTotal.service.TransactionService;
import sanrenxing.dayEnd.backRepertoryTotal.utils.ExclUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @desrciption 行情数据 核心控制器
 * @auth：yidu  李小锋
 * @date:2021/3/13 0013 - 16:12
 * @version:1:0
 */
@Controller
@RequestMapping("/marketdates")
public class MarketDataController {
    //自动装配
    @Autowired
    //调用行情数据业务层
    private MarketDataService marketDataService;
    //调用证券交易数据业务层对象
    @Autowired
    private TransactionService transactionService;
    /**
     * 分页查询
     * @param req 请求对象
     * @param page 页数
     * @param limit 行数
     * @return 返回map集合从后端填充数据到前端
     */
    @GetMapping("/MarketDatas")
    @ResponseBody
    public Map<String,Object> selectEquity(HttpServletRequest req, int page, int limit){
        //构造一个新对象用于保存
        MarketData marketData = new MarketData();
        //接收来自请求中的权益除权日inputDate
        String inputDate = req.getParameter("inputDate");
        //判断不为空切不等于零
        if(inputDate!=null && inputDate.trim().length()!=0){
            //创建一个日期String转换为日期格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //保存权益数据
            try {
                //将请求中的进行格式对象封装到行情数据对象
                marketData.setInputDate(sdf.parse(inputDate));
            } catch (ParseException e) {
                //异常信息打印
                e.printStackTrace();
            }
        }
        //调用数据方法根据权证对象构造多条件数据
        String getcondition = marketDataService.getcondition(marketData);
        //执行多条件查询分页
        List<MarketData> dataList = marketDataService.findByPage(limit, page, getcondition);
        //多表查询表中总记录数
        int count = marketDataService.count(getcondition);
        //定义映射集合对象
        HashMap<String, Object> marketMap = new HashMap<>();
        //在映射集合中添加key为code，值为0的状态码
        marketMap.put("code",0);
        //在映射集合中添加key为msg,值为响应信息字符串
        marketMap.put("msg","");
        //在映射集合中添加key为data,值为员集合对象
        marketMap.put("data",dataList);
        //在映射集合中添加key为count,值总行数的数据对
        marketMap.put("count",count);
        //证券名称SecuritiesInfomationLXF
        marketMap.put("secName",transactionService.SecuritiesInfomationLXF());
        //向前端发送数据
        return marketMap;
    }
    /**
     * 新增方法
     * @param marketData 对象
     * @return 0,failure 1，SUCCESS
     */
    @PostMapping("/MarketDatas")
    @ResponseBody
    public String add(@RequestBody MarketData marketData){
        //获取添加的行数
        int rows = marketDataService.add(marketData);
        //使用三元运算符判断
        return rows>0?"add SUCCESS":"add failure";
    }
    /**
     * 删除方法
     * @param marketId 证券编号
     * @return 0,failure 1，SUCCESS
     */
    @DeleteMapping("/MarketDatas/{marketId}")
    @ResponseBody
    //PathVariable：接收请求路径中占位符的值括号中可有可无但是必须一样
    public String add(@PathVariable("marketId") int marketId){
        //获取删除的行数
        int rwos=marketDataService.delete(marketId);
        //使用三元运算符判断
        return rwos>0?"delete SUCCESS":"delete failure";
    }
    /**
     * 修改方法方法
     * @param marketData 对象
     * @return 0,failure 1，SUCCESS
     */
    @Update("/MarketDatas")
    @ResponseBody
    //RequestBody:表示前端传递的json格式转化为javaBean即domain
    //ResponseBody:表示后端传递的javaBean格式转化为json格式
    public String update(@RequestBody MarketData marketData){
        //获取修改的行数
        int rwos=marketDataService.update(marketData);
        //使用三元运算符判断
        return rwos>0?"update SUCCESS":"update failure";
    }

    /**
     * 批量删除
     * @param MarketIdStr 数据证券ID
     * @return 0,failure 1，SUCCESS
     */
    @PutMapping("/batchBel/{MarketIdStr}")
    @ResponseBody
    public String batchBeleteById(@PathVariable("MarketIdStr") String MarketIdStr) {
        //对员工编号字符串按逗号分隔split
        String[] empNos = MarketIdStr.split(",");
        //定义返回值
        String result = "delete success";
        //循环遍历出证券数据id
        for (String equityData : empNos) {
            //调用业务层删除
            int rows = marketDataService.delete(Integer.parseInt(equityData));
            //判断为空
            if (rows <= 0) {
                //发送错误信息
                return "batch delete failure";
            }
        }
        //发送数据
        return result;
    }

    /**
     * ex
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/form")
    public String form(HttpServletRequest request)throws Exception{
        //ModelAndView modelAndView = new ModelAndView();
        //modelAndView.setViewName("/html/MarketDatas.html");
        //创建MultipartHttpServletRequest spring文件对象等于request转
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        //定义输入流对象
        InputStream in =null;
        //创建一个list集合嵌套list集合
        List<List<Object>> listob = null;
        //创建MultipartFile 上传文件gfile上传对象 upfile
        MultipartFile file = multipartRequest.getFile("upfile");
        //判断文件是否存在isempty
        if(file.isEmpty()){
            //抛出异常错误信息t n Ex
            throw new Exception("文件不存在！");
        }
        //实例化输入流对象getinput
        in = file.getInputStream();
        //变量于创建Eils对象点getBanByExc)流,file.getoriginalfilename文件名;
        listob = new ExclUtils().getBankListByExcel(in,file.getOriginalFilename());
        //关闭流
        in.close();
        //创建一个日期转换格式sdf
        SimpleDateFormat Sdf=new SimpleDateFormat("yyyy-MM-dd");
        //1.该处可调用service相应方法进行数据保存到数据库中，现只对数据输出
        //2.循环
        for (int i = 0; i < listob.size(); i++) {
            //创建一个存储集合对象类型get
            List<Object> lo = listob.get(i);
            //创建一个行情对象MarketDataT
            MarketDataT marketData = new MarketDataT();
            //marketData.setMarketId(((Double)lo.get(0)).intValue());
            //String mark=lo.get(0).toString();
            //int markInt= (int)Double.parseDouble(lo.get(0).toString());
            //将元素0封装到MarketId
            marketData.setMarketId((int)Double.parseDouble(lo.get(0).toString()));
            //将元素封装到SeId
            marketData.setSeId(String.valueOf(lo.get(1)));
            //将元素封装到InputDate
            marketData.setInputDate(String.valueOf(lo.get(2)));
            //将元素封装到OpenPrice
            marketData.setOpenPrice(Double.parseDouble(lo.get(3).toString()));
            //将元素封装到ClosePrice
            marketData.setClosePrice(Double.parseDouble(lo.get(4).toString()));
            //将元素封装到Notes
            marketData.setNotes(lo.get(5).toString());
            //调用excl导入方法
            marketDataService.exclMethod(marketData);
        }
        //发送视图redirect:/html/MarketDatas.html
        return "redirect:/html/MarketDatas.html";
    }

}
